/*
 * @Author: xuanxiaoqian
 * @Date: 2022-12-04 15:35:39
 * @LastEditTime: 2022-12-05 20:17:34
 * @LastEditors: xuanxiaoqian
 * @Description: 请求拦截器
 */

import { useUserStore } from '@/store/modules/userStore'
import { defaultConfig } from './defaultConfig'

type ResultData = {
  code: 200 | -1

  msg: string

  data?: Array<any> | any
}

class Http {
  get(url: string, params?: any): Promise<ResultData> {
    const { userInfo } = useUserStore()
    const vailData = { talive_token: userInfo?.token ?? null }

    return new Promise((resolve, reject) => {
      uni.request({
        url: `${defaultConfig.baseURL + url}`,
        data: params,
        method: 'GET',
        timeout: defaultConfig.timeout,
        header: Object.assign(defaultConfig.headers, vailData),
        success: function (res) {
          resolve(res.data as any)
        },
        fail: function (err) {
          reject(err)
        },
      })
    })
  }

  post(url: string, params?: any): Promise<ResultData> {
    const { userInfo } = useUserStore()
    const vailData = { talive_token: userInfo?.token ?? null }

    return new Promise((resolve, reject) => {
      uni.request({
        url: `${defaultConfig.baseURL + url}`,
        data: params,
        method: 'POST',
        timeout: defaultConfig.timeout,
        header: Object.assign(defaultConfig.headers, vailData),
        success: function (res) {
          resolve(res.data as any)
        },
        fail: function (err) {
          reject(err)
        },
      })
    })
  }
}

const http = new Http()
export default http
